package com.ysm.smfu.chat;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.StatusBarCompat;
import com.ysm.smfu.activity.FoundActivity;
import com.ysm.smfu.activity.PayActivity;
import com.ysm.smfu.bean.Friends;
import com.ysm.smfu.bean.SysMsg;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.fragment.MyBaseFragment;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.PopupWindowUtil;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ThreadUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.view.SegmentGroupHelper;
import com.ysm.smfu.view.SegmentedGroup;
import com.ysm.smfu.welcome.SharedConfig;
import com.ysm.smfu.zxing.activity.CaptureActivity;
import com.hyphenate.chat.EMClient;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chatuidemo.DemoHelper;
import chatuidemo.activity.AddFriendsActivity;
import chatuidemo.activity.ZHSearchActivity;
import chatuidemo.db.DBManager;
import chatuidemo.runtimepermissions.PermissionsManager;

public class ZHChatFragment extends MyBaseFragment {

    @BindView(R.id.main_bottom)
    AutoRelativeLayout main_bottom;
    @BindView(R.id.addF)
    ImageView addF;
    //    @BindView(R.id.btn_conversation)
//    TextView btnConversation;
//    @BindView(R.id.btn_friend)
//    TextView btnFriend;
    @BindView(R.id.segmentGroup)
    SegmentedGroup segmentedGroup;

    private ZHConversationListFragment zhConversationListFragment;
    private ZHContactListFragment zhContactListFragment;
    private FragmentTransaction trx;
    private Intent intent;
    //    是否需要更新好友变化
    boolean isNeedContact = true;
    private String petName;
    private MyReceiver myReceiver;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = UIUtils.inflate(R.layout.fragment_chat);
        ButterKnife.bind(this, view);
        initTopBar();
        getConfig();
        initView();
        initSegment();
        registerForLoginedLoadData();
//        主动添加好友时，需要时刻获取好友变化.但是主动添加好友之后，并不知道好友会拒绝还是添加，同时没有返回信息，无法判断添加状态，从而无法控制获取好友的开关

//        registerForContactList();
//        在第一次获取到申请联系人之后，保存到数据库，下次再有申请联系人只需要插入一条即可，不需要操作整张表，但是因为没有返回新申请好友，无法逐条获取，只能一次获取所有申请人，再插入
//        registerForShenQingContact();
        return view;
    }

    /**
     * 沉浸式状态栏实现
     */
    private void initTopBar() {
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        StatusBarCompat.compat(getActivity(), getResources().getColor(R.color.green));
        AutoLinearLayout.LayoutParams layoutParams = (AutoLinearLayout.LayoutParams) main_bottom.getLayoutParams();
        layoutParams.topMargin = StatusBarCompat.getStatusBarHeight(getContext());
        main_bottom.setLayoutParams(layoutParams);
//        }
    }

    /**
     * 注册广播，在登录完成后加载数据
     */
    private void registerForLoginedLoadData() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("loginedGoLoadData");
        myReceiver = new MyReceiver();
        getActivity().registerReceiver(myReceiver, intentFilter);
    }

    //是否登录成功
    boolean isLogined;

    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            isLogined = true;
        }
    }

    /**
     * 初始化顶部选择器
     */
    private void initSegment() {
        ArrayList<String> mNames = new ArrayList<>();
        mNames.add("消息");
        mNames.add("好友");

        RadioButton radioButton = SegmentGroupHelper.createRadioButton(getActivity(), R.id.one, mNames.get(0));
        segmentedGroup.addView(radioButton);
        RadioButton radioButton2 = SegmentGroupHelper.createRadioButton(getActivity(), R.id.two, mNames.get(1));
        segmentedGroup.addView(radioButton2);

        segmentedGroup.check(R.id.one);
        segmentedGroup.updateBackground(); // 更新背景颜色的核心方法，不要忘记调用
        // 设置点击监听
        segmentedGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                trx = getActivity().getSupportFragmentManager().beginTransaction();
                switch (checkedId) {
                    case R.id.one:
                        trx.hide(zhContactListFragment).show(zhConversationListFragment).commit();
                        zhConversationListFragment.fresh();
                        break;
                    case R.id.two:
                        trx.hide(zhConversationListFragment).show(zhContactListFragment).commit();
                        getContactData();
                        break;
                }
            }
        });
    }

    /**
     * 是否已经保存过申请联系人
     */
    Boolean isHasLoadShenQingContact;

    /**
     * 在第一次获取到申请联系人之后，保存到数据库，下次再有申请联系人只需要插入一条即可，不需要操作整张表
     */
    private void registerForShenQingContact() {
        getActivity().getContentResolver().registerContentObserver(Uri.parse("content://dmh.sq_contact"), true, observer);
    }

    private ContentObserver observer = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            isHasLoadShenQingContact = true;
        }
    };

    private void getConfig() {
        SharedPreferences sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        String name = sp.getString(SpKey.NAME, "");
        SharedPreferences currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        petName = currShared.getString(SpKey.NC, "");
    }

    //    更新好友变化
//    private void registerForContactList() {
//        IntentFilter intent = new IntentFilter();
//        intent.addAction("updateFriendList");
//        getActivity().registerReceiver(new Myreceiver(), intent);
//    }

//    class Myreceiver extends BroadcastReceiver {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            isNeedContact = true;
//        }
//    }

    private void initView() {
        // btnFriend.setSelected(true);
        zhConversationListFragment = new ZHConversationListFragment();
        zhContactListFragment = new ZHContactListFragment();
        //默认显示消息页，隐藏好友页
        getActivity().getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, zhConversationListFragment)
                .add(R.id.fragment_container, zhContactListFragment)
                .hide(zhContactListFragment).show(zhConversationListFragment).commit();
    }

    @OnClick({R.id.addF})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.addF:
                View popup = PopupWindowUtil.togglePopup("ZHChatFragment", R.layout.popup_addf_ss,
                        addF, 5);
                if (isFirst)
                    setPopupListenter(popup);
                break;
        }
    }

    boolean isFirst = true;

    /**
     * 设置popupWindow中监听事件
     */
    private void setPopupListenter(View view) {
        isFirst = false;
        LinearLayout addFre = (LinearLayout) view.findViewById(R.id.popup_addFre);
        LinearLayout saoYSao = (LinearLayout) view.findViewById(R.id.popup_saoYSao);

        /**
         * 添加好友
         */
        addFre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BaseProtocal.isGoLogin(true, getActivity()))
                    UIUtils.startActivity(ZHSearchActivity.class);
                PopupWindowUtil.cancel("ZHChatFragment", null);
            }
        });

        /**
         * 扫一扫
         */
        saoYSao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BaseProtocal.isGoLogin(true, getActivity())) {
                    Intent openCameraIntent = new Intent(getActivity(), CaptureActivity.class);
                    startActivityForResult(openCameraIntent, 0);
                }
                //打开扫描界面扫描条形码或二维码

//                点击跳转之后取消pw
                PopupWindowUtil.cancel("ZHChatFragment", null);
            }
        });
    }

    /**
     * 扫码成功后回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (intent == null) {
            intent = new Intent(getActivity(), PayActivity.class);
            intent.putExtra("pay", 1);
        }
        //处理扫描结果（在界面上显示）
        if (resultCode == getActivity().RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            String[] split = scanResult.split("\\?");
            if (TextUtils.equals(split[0], "type:addFriend")) {
                //  添加好友,传递用户Id
                UIUtils.startActivity(AddFriendsActivity.class, SpKey.USERID, split[1]);

            } else if (TextUtils.equals(split[0], "type:payMoney") || TextUtils.equals(split[0], "type:payPoints")) {
//              付款
                payMoneyAndJiFen(split[1]);
            } else if (TextUtils.equals(split[0], "type:payPre")) {
//                        预付款，自己输入金额
                prePay(split[1]);
                // 付款标志
            } else {
                Intent intent = new Intent(getActivity(), FoundActivity.class);
                intent.putExtra("found", 4);
                intent.putExtra(SpKey.INVITURL, scanResult);
                startActivity(intent);
            }
        }
    }

    /**
     * 付款
     */
    private void payMoneyAndJiFen(String dingdanInfo) {
        String[] split = dingdanInfo.split("#");
        intent.putExtra(SpKey.Pay_BUSSINESSID, split[0]);
        intent.putExtra(SpKey.MONEY, split[1]);
        intent.putExtra(SpKey.JIFEN, split[2]);
        intent.putExtra(SpKey.REMARK, split[3]);
        startActivity(intent);
    }

    /**
     * 预付款
     */
    private void prePay(String businessId) {
        intent.putExtra(SpKey.MONEY, "");
        intent.putExtra(SpKey.JIFEN, "");
        intent.putExtra(SpKey.Pay_BUSSINESSID, businessId);
        startActivity(intent);
    }

    /**
     * 获取联系人相关数据
     */
    private void getContactData() {
        getSQFriends();
        getRobotMsg();
        //异步获取好友列表
        // if (isNeedContact)
        getContactList();
    }

    @Override
    public void refresh() {
        if (getActivity() == null || getActivity().getSupportFragmentManager() == null)
            return;
        // 切换为消息界面
        trx = getActivity().getSupportFragmentManager().beginTransaction();
        trx.hide(zhContactListFragment).show(zhConversationListFragment).commitAllowingStateLoss();
        segmentedGroup.check(R.id.one);
        if (BaseProtocal.isGoLogin(true))
            return;
        zhConversationListFragment.fresh();
    }

    @Override
    public void afterOnResume() {
        super.afterOnResume();
        if (BaseProtocal.isGoLogin(true)) {
            resetData();
            return;
        }
        if (isLogined) {
            getContactData();
            isLogined = false;
        }
        if (TextUtils.isEmpty(petName))
            getConfig();
        else if (!isNickSetSuccess) {
            setIOSNick(petName);
        }
    }

    /**
     * 重置状态
     */
    private void resetData() {
        zhContactListFragment.clearContact();
        zhConversationListFragment.clearConversation();
    }

    public void refreshConversation() {
        if (zhConversationListFragment != null)
            zhConversationListFragment.fresh();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    boolean isNickSetSuccess;

    /**
     * 获取好友申请数据
     */
    private void getSQFriends() {
        BaseProtocal.builder(true).getSQFriends(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("好友申请", response);
                if (TextUtils.isEmpty(response))
                    return;
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String state = jsonObject.optJSONObject("result").optString("state");
                    if (TextUtils.equals(state, "1")) {
                        int apply_size = jsonObject.optInt("apply-size");
                        zhContactListFragment.setUnreadMsgNumber(apply_size);
                        Friends friends = new Gson().fromJson(response, Friends.class);
                        if (friends.user != null)
                            DBManager.getInstance().saveShenQingContact(friends.user);
                    }
                } catch (JSONException e) {
                }
            }

            @Override
            public void onFail(Exception e) {
            }
        });
    }

    /**
     * 获取系统消息
     * user/getSystemMessage
     * id: 用户id
     *
     * @return
     */
    public void getRobotMsg() {
        BaseProtocal.builder(true).getRobotMsg(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("获取系统消息", response);
                if (TextUtils.isEmpty(response))
                    return;
                SysMsg sysMsg = new Gson().fromJson(response, SysMsg.class);
                if (sysMsg != null && sysMsg.message != null && sysMsg.message.size() > 0) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        int unread_size = jsonObject.optInt("unread-size");
                        zhContactListFragment.setUnReadSysMsgNumber(unread_size);
                    } catch (JSONException e) {
                    }
                    DBManager.getInstance().saveSysMsg(sysMsg);
                }
            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }

    /**
     * 获取好友列表，进入时和添加好友或者同意好友时更新
     */
    public void getContactList() {
        BaseProtocal.builder(true).getContactListFromOnLine(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("好友列表", response);
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
//                    isNeedContact = false;
                    Friends friends = new Gson().fromJson(response, Friends.class);
                    DBManager.getInstance().saveContactList2(friends.user);
                }
            }

            @Override
            public void onFail(Exception e) {

            }
        });
    }

    public void setIOSNick(final String nick) {
        ThreadUtils.runOnBackThread(new Runnable() {
            @Override
            public void run() {
                boolean updatenick = EMClient.getInstance().updateCurrentUserNick(nick);
                if (!updatenick) {
                    isNickSetSuccess = false;
                } else {
                    boolean updatenick2 = DemoHelper.getInstance().getUserProfileManager().updateCurrentUserNickName(nick);
                    if (!updatenick2) {
                        isNickSetSuccess = false;
                    } else {
                        isNickSetSuccess = true;
                    }
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(myReceiver);
    }
}
